<template>
  <div class="container">
    <div class="header">
      <img src="@/assets/bcg-image/header.png" alt="页面头部装饰" />
      <div class="timer">
        <span>{{ formattedDate }}</span
        ><br />
        <span>{{ formattedTime }}</span>
      </div>
      <div class="city-name">
        <span>智慧城市-{{ cityName }}</span>
      </div>
    </div>

    <RouterView v-if="isMapReady" />

    <div id="map"></div>
    <button class="navigation" @click="toggleDirections">导航</button>
    <div ref="directionsContainer" class="directions-container"></div>

    <div class="footer">
      <img src="@/assets/bcg-image/xzd-header.png" alt="页面底部装饰" />
    </div>
    <div class="footer-buttons">
      <div class="rotate" @click="toggleRotation">
        <img src="./assets/icons/地球自转.png" alt="" :class="{ 'rotating-active': isRotating }" />
        <span>自转</span>
      </div>
      <div class="rotate" @click="handelPlot">
        <img src="./assets/icons/控制台.png" alt="" />
        <span>控制台</span>
      </div>
      <div class="rotate" @click="handelCity">
        <img src="./assets/icons/plane.png" alt="" />
        <span>城市视图</span>
      </div>
      <div class="rotate" @click="handelsearch">
        <img src="./assets/icons/查询.png" alt="" />
        <span>查询</span>
      </div>
      <div class="rotate" @click="handelbridge">
        <img src="./assets/icons/11桥梁.png" alt="" />
        <span>桥梁</span>
      </div>
      <div class="rotate">
        <el-popover placement="top" trigger="hover" popper-class="custom-popover">
          <template #reference>
            <img src="./assets/icons/测量.png" alt="" />
          </template>
          <div class="measure-container">
            <img src="./assets/icons/-_折线.png" alt=""  @click="handelline"/>
            <img src="./assets/icons/正方形.png" alt=""  @click="handelrectangle"/>
            <img src="./assets/icons/多边形.png" alt=""  @click="handelpolygon" />
            <img src="./assets/icons/圆形未选中.png" alt=""  @click="handelcircle" />
          </div>
        </el-popover>
        <span>测量距离</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, provide, ref, onUnmounted } from 'vue'
import mapbox from 'mapbox-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
import { Scene, Zoom, Fullscreen, MouseLocation, MapTheme, Scale, Logo } from '@antv/l7'
import { Mapbox } from '@antv/l7-maps'
import MapboxDirections from '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions'
import '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css'
import { useRouter } from 'vue-router'
// 地图API密钥
mapbox.accessToken =
  'pk.eyJ1IjoieHpkbWFwZ2lzIiwiYSI6ImNtOWtxbXU3eTBwcGEya3BvYW9ubWZ6bWwifQ.bn8nv2PPHfWDeDWExmQamQ'

// 响应式数据
const formattedTime = ref('')
const formattedDate = ref('')
const cityName = ref('武汉')
let map = null
let scene = null
const directionsVisible = ref(false)

const directionsContainer = ref(null)
// 自转相关状态
const isRotating = ref(true) // 初始为自转状态
let rotateAnimationId = null // 存储 requestAnimationFrame ID
const rotateSpeed = 0.05 // 自转速度（数值越大越快）
const isMapReady = ref(false)
const mapScene = ref({ map: null, scene: null });

let directionsControl = new MapboxDirections({
  accessToken: mapbox.accessToken,
  className: 'custom-directions-control',
})
// 使用 requestAnimationFrame 实现地图自转
const animateRotation = () => {
  if (!isRotating.value || !map) return

  // 获取当前地图中心点和旋转角度
  // 获取当前地图的中心点
  const center = map.getCenter()

  center.lng += rotateSpeed // 增加旋转角度
  // 变化后的中心点
  map.setCenter(center)

  // 继续下一帧
  rotateAnimationId = requestAnimationFrame(animateRotation)
}

// 开始地图自转
const startRotation = () => {
  if (rotateAnimationId || !map) return

  isRotating.value = true
  rotateAnimationId = requestAnimationFrame(animateRotation)
}

// 停止地图自转
const stopRotation = () => {
  if (rotateAnimationId) {
    cancelAnimationFrame(rotateAnimationId)
    rotateAnimationId = null
  }
  isRotating.value = false
}
const router = useRouter()
// 切换自转状态
const toggleRotation = () => {
  if (isRotating.value) {
    stopRotation()
  } else {
    startRotation()
  }
  router.push('/')
  if (map) {
    map.setZoom(1) // Mapbox GL的setZoom方法设置缩放级别
  }
}

// 控制台

const handelPlot = () => {
  router.push('/plot')
  // 停止地图自转
  stopRotation()
    if (map) {
    map.setZoom(1)
  }
}
// 城市视图
const handelCity = () => {
  if (!isMapReady.value) {
    console.warn('地图尚未就绪，请等待初始化完成');
    return;
  }
  router.push('/cityview');
  stopRotation();
};
// 查询
const handelsearch = () => {
  router.push('/search');
  stopRotation();
}
// 桥梁
const handelbridge = () => {
  router.push('/bridge');
  stopRotation();
}
// 线
const handelline = () => {
  router.push('/messure/line');
  stopRotation();
}
// 矩形
const handelrectangle = () => {
  router.push('/messure/rect');
  stopRotation();
}
// 多边形
const handelpolygon = () => {
  router.push('/messure/polygon');
  stopRotation();
}
// 圆
const handelcircle = () => {
  router.push('/messure/circle');
  stopRotation();
}


// 初始化地图
const initMap = () => {
  return new Promise((resolve, reject) => {
    try {
      map = new mapbox.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/dark-v11',
        center: [116.46, 39.92],
        projection: 'globe',
        zoom: 1,
      })

      map.on('load', () => {
        // 设置地图雾效和星空效果
        map.setFog({
          'high-color': 'rgb(36, 92, 223)',
        })

        resolve(map)
      })

      map.on('error', (e) => {
        console.error('地图加载错误:', e)
        reject(e)
      })
    } catch (error) {
      console.error('初始化地图失败:', error)
      reject(error)
    }
  })
}

// 初始化L7场景
const initScene = (mapInstance) => {
  return new Promise((resolve) => {
    scene = new Scene({
      id: 'map',
      map: new Mapbox({
        mapInstance,
      }),
      logoVisible: false,
    })
    const customOptions = [
      {
        text: '标准地图',
        value: 'mapbox://styles/mapbox/standard',
        img: 'src/assets/bcg-image/标准地图.png',
      },
      {
        text: '标准卫星地图',
        value: 'mapbox://styles/mapbox/standard-satellite',
        img: 'src/assets/bcg-image/标准卫星地图.png',
      },

      {
        text: '深色地图道路',
        value: 'mapbox://styles/mapbox/navigation-night-v1',
        img: 'src/assets/bcg-image/屏幕截图 2025-07-28 125530.png',
      },
      {
        text: '卫星地图道路',
        value: 'mapbox://styles/mapbox/satellite-streets-v12',
        img: 'src/assets/bcg-image/屏幕截图 2025-07-28 125509.png',
      },
      {
        text: '白天地图道路',
        value: 'mapbox://styles/mapbox/navigation-day-v1',
        img: 'src/assets/bcg-image/屏幕截图 2025-07-28 125436.png',
      },
    ]
    // 创建比例尺控件实例
    const scale = new Scale({
      maxWidth: 150, // 比例尺最大宽度
      position: 'bottomright', // 显示位置：右下角
      className: 'custom-scale', // 自定义样式类名
    })
    let scaleAdded = false
    scene.on('loaded', () => {
      // 添加自定义缩放控件
      const zoomControl = new Zoom({
        position: 'topleft',
        className: 'custom-zoom',
      })
      const fullscreen = new Fullscreen({
        position: 'topright',
        className: 'custom-fullscreen',
      })

      const mouseLocation = new MouseLocation({
        transform: (position) => {
          const [lng, lat] = position

          // 分别对经度、纬度保留四位小数，并拼接成字符串
          const formattedLng = lng.toFixed(4) // 经度保留四位小数
          const formattedLat = lat.toFixed(4) // 纬度保留四位小数

          // 返回格式化后的经纬度（格式可自定义，如“经度: xxx, 纬度: xxx”）
          return [formattedLng, formattedLat]
        },
        position: 'bottomright',
        className: 'custom-mouse-location',
      })
      const mapTheme = new MapTheme({
        options: customOptions,
        position: 'bottomleft',
        className: 'custom-map-theme',
      })

      /// 监听地图缩放事件
      mapInstance.on('zoom', () => {
        const currentZoom = mapInstance.getZoom()

        // 当缩放级别 >14 时添加比例尺
        if (currentZoom > 4) {
          // 仅在未添加时执行添加操作
          if (!scaleAdded) {
            // 用标记变量替代 hasControl
            scene.addControl(scale)
            scaleAdded = true // 更新标记状态
          }
        } else {
          // 当缩放级别 ≤14 时移除比例尺
          if (scaleAdded) {
            // 用标记变量替代 hasControl
            scene.removeControl(scale)
            scaleAdded = false // 更新标记状态
          }
        }
      })

      // 初始化时触发一次缩放事件，检查初始状态
      mapInstance.fire('zoom')

      // 添加logo控件
      const logo = new Logo({
        // 图片 url
        img: 'http://www.x-zd.com/themes/simpleboot3_web/public/web/images/image/logo_03.png',
        href: 'http://www.x-zd.com/',
      })

      scene.addControl(logo)
      scene.addControl(mapTheme)

      scene.addControl(mouseLocation)

      scene.addControl(fullscreen)
      scene.addControl(zoomControl)

      resolve(scene)
    })
  })
}

const toggleDirections = () => {
  if (!directionsControl || !map || !directionsContainer.value) {
    console.log('控件或容器未准备好')
    return
  }

  directionsVisible.value = !directionsVisible.value

  if (directionsVisible.value) {
    // 添加控件：先确保控件未被添加，再调用 onAdd 获取 DOM 并添加
    if (!directionsControl._isAdded) {
      const controlElement = directionsControl.onAdd(map)
      directionsContainer.value.appendChild(controlElement)
      directionsControl._isAdded = true // 标记已添加
    }
  } else {
    // 移除控件：先调用 onRemove 清理状态，再移除 DOM
    if (directionsControl._isAdded) {
      directionsControl.onRemove(map) // 清理控件内部状态
      const controlElement = directionsControl._container
      if (controlElement && directionsContainer.value.contains(controlElement)) {
        directionsContainer.value.removeChild(controlElement)
      }
      directionsControl._isAdded = false // 标记已移除
    }
  }
}
// 更新日期时间
const updateDateTime = () => {
  const date = new Date().toLocaleDateString()
  const time = new Date().toLocaleTimeString()
  formattedDate.value = date
  formattedTime.value = time
}

onMounted(async () => {
  try {
    // 初始化地图
    const mapInstance = await initMap()

    // 初始化L7场景
     const sceneInstance = await initScene(mapInstance);

    mapScene.value.map = mapInstance;
    mapScene.value.scene = sceneInstance;
 isMapReady.value = true;
    // 初始化日期时间
    updateDateTime()

    // 每秒更新一次时间
    setInterval(updateDateTime, 1000)

    // 每秒更新一次时间
    setInterval(updateDateTime, 1000)

    // 初始启动自转
    startRotation()

    // 监听路由变化，切换控制台
    router.afterEach(() => {
      if (router.currentRoute.name === 'plot') {
        handelPlot()
      }
      if (router.currentRoute.name === 'cityview') {
        handelCity()
      }
      if (router.currentRoute.name ==='search') {
        handelsearch()
      }
      if (router.currentRoute.name === 'bridge') {
        handelbridge()
      }
      if (router.currentRoute.name ==='messure') {
        handelline()
        handelrectangle()
        handelpolygon()
        handelcircle()
      }

    })
  } catch (error) {
    console.error('地图初始化失败:', error)
    // 可以在这里添加错误提示UI
  }
})
 provide('mapScene', mapScene)
// 组件卸载时清理资源
onUnmounted(() => {
  // 释放地图资源
  if (scene) {
    scene.destroy()
    scene = null
  }

  if (map) {
    map.remove()
    map = null
  }
  directionsControl = new MapboxDirections({
    accessToken: mapbox.accessToken,
  })
  // 停止自转定时器
  stopRotation()
})
</script>

<style scoped>
.container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.header {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  z-index: 2;
}
.header img {
  width: 100%;
  height: 100%;
}
.footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 70px;
  transform: rotate(180deg);
}
.footer img {
  width: 100%;
  height: 100%;
}
.timer {
  position: absolute;
  top: 5px;
  left: 70px;
  font-size: 16px;
  color: #fff;
  font-weight: bolder;
}
.city-name {
  position: absolute;
  top: 10px;
  right: 575px;
  font-size: 18px;
  color: #fff;
  font-weight: bolder;
}
#map {
  position: relative;
  width: 100%;
  height: 100vh;
}
#map ::v-deep .l7-control-zoom.custom-zoom {
  position: absolute !important;
  top: 60px !important; /* 距离地图顶部 80px（避开 header） */
  left: 10px !important; /* 距离地图左侧 30px */
  z-index: 100 !important; /* 确保不被其他元素遮挡 */
}
#map ::v-deep .custom-fullscreen {
  top: 60px !important; /* 右上角顶部 */
  right: 10px !important; /* 右上角右侧 */
  position: absolute !important;
  z-index: 999 !important;
}

#map ::v-deep .custom-map-theme {
  bottom: 30px !important;
  left: 10px !important;
  position: absolute !important;
  z-index: 1001 !important; /* 提高到更高的层级 */
}

#map ::v-deep .custom-mouse-location {
  bottom: 30px !important; /* 距离底部 80px（避开 footer） */
  right: 10px !important;
  position: absolute !important;
  z-index: 999 !important;
  text-align: center;
}
.navigation {
  position: absolute;
  top: 140px;
  left: 17px;
  padding: 5px 10px;
}
.navigation {
  position: absolute;
  top: 140px;
  left: 17px;
  padding: 5px 10px;
  cursor: pointer;
  z-index: 999; /* 确保按钮在最上层 */
}
/* 可添加激活状态样式 */
.navigation.active {
  background-color: #42b983;
  color: white;
}
.directions-container {
  position: absolute;
  top: 200px; /* 精确控制位置 */
  left: 20px;
  width: 300px;
  z-index: 1000;
}
.footer-buttons {
  position: absolute;
  display: flex;
  bottom: -8px;
  left: 455px;
  z-index: 999;
  color: #fff;
}
.footer-buttons .rotate {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 10px;
}
.footer-buttons .rotate img {
  width: 30px;
  height: 30px;
  padding: 5px;
  background-color: rgb(49, 49, 241);
  border-radius: 50%;
}
.footer-buttons .rotate span {
  font-size: 12px;
}
#map ::v-deep .custom-scale {
  position: absolute !important;
  bottom: 60px !important; /* 距离底部60px（避开footer） */
  right: 10px !important; /* 与鼠标位置控件对齐右侧 */
  z-index: 999 !important;
}
</style>
<style>
.el-popover.custom-popover {
  /* 核心：设置透明背景 */
  background-color: transparent !important;
}

/* 弹出层内部内容 */
.measure-container {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.measure-container img {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.measure-container img:hover {
  transform: scale(1.1); /* 悬停放大 */
}
</style>
